<template>
  <div class="login-box">
    <el-form
      v-if="isShowL"
      ref="loginFormRef"
      :model="loginForm"
      status-icon
      :rules="rules"
      label-width="70px"
      class="loginForm">
      <h1>User login</h1>
      <el-form-item label="账 号：" prop="account">
        <el-input v-model="loginForm.account" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密 码：" prop="password">
        <el-input v-model="loginForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="验 证：" prop="yanzhengma">
        <template>
          <div class="code_box">
            <el-input
              type="text"
              placeholder="请输入验证码"
              v-model.trim="loginForm.code"
              @keyup.native.enter="login" />
            <canvas id="canvas" width="100px" height="33px" @click="handleCanvas"></canvas>
          </div>
        </template>
      </el-form-item>
      <el-form-item>
        <el-button class="sub-btn" type="primary" @click="login">登陆</el-button>
        <el-button class="sub-btn" type="success" @click="registerBox">注册</el-button>
      </el-form-item>
    </el-form>
    <el-form
      v-if="isShowR"
      :model="ruleForm"
      ref="ruleForm"
      status-icon
      :rules="rules"
      label-width="85px"
      class="loginForm">
      <h1>User register</h1>
      <el-form-item label="账号:" prop="account">
        <el-input v-model="ruleForm.account" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input type="password" v-model="ruleForm.password" autocomplete="off" ref="onePass"></el-input>
      </el-form-item>
      <el-form-item label="确认密码:" prop="checkPass">
        <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off" ref="twoPass"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="sub-btn" type="primary" @click="loginBox">登陆</el-button>
        <el-button class="sub-btn" type="success" @click="register('ruleForm')">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { userLogin, userReg } from '@/api/user'
import { draw } from '@/views/common/code.js'
export default {
  name: 'Login',
  data() {
    const validCode = (rule, value, callback) => {
      if (!this.loginForm.code) {
        callback('请输入验证码')
      } else {
        callback()
      }
    }
    return {
      rules: {
        account: [
          { required: true, message: '请输入用户账号', trigger: 'blur' },
          { min: 6, max: 24, message: '用户账号长度在6-24位', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 24, message: '用户密码长度在6-24位', trigger: 'blur' },
        ],
        checkPass: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { min: 6, max: 24, message: '密码要同上一致', trigger: 'blur' },
        ],
        yanzhengma: [{ required: true, validator: validCode, trigger: 'blur' }],
      },
      loginForm: {
        account: '',
        password: '',
        code: '',
        code_arr: [],
        true_code: '',
      },
      ruleForm: {
        account: '',
        password: '',
        checkPass: '',
      },
      isShowR: false,
      isShowL: true,
    }
  },
  mounted() {
    this.loginForm.true_code = draw(this.loginForm.code_arr)
  },
  methods: {
    handleCanvas() {
      this.loginForm.true_code = draw(this.loginForm.code_arr)
    },
    login() {
      this.$refs.loginFormRef.validate((valid) => {
        if (!valid) return
        if (this.loginForm.code !== this.loginForm.true_code) return this.$message.error('验证码错误！')
        userLogin(this.loginForm).then((data) => {
          // console.log(data)
          if (data.status != 0) {
            this.$message.error(data.message)
          } else {
            window.sessionStorage.setItem('token', data.token)
            this.$store.commit('setUser', data.data)
            // 如果当前url携带参数有redirect字段 就跳转到对应的页面 否则跳转首页
            const redirect = this.$route.query.redirect
            if (redirect) {
              // decodeURIComponent() 方法用于解码由 encodeURIComponent 方法或者其它类似方法编码的部分统一资源标识符（URI）。
              this.$router.replace(decodeURIComponent(redirect))
            } else {
              this.$router.replace('/user')
            }
          }
        })
      })
    },
    register(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return this.$message.error('注册失败！')
        } else if (valid) {
          console.log(valid)
          const onePass = this.$refs.onePass.value
          const twoPass = this.$refs.twoPass.value
          if (onePass != twoPass) {
            return this.$message.error('密码不一致！')
          } else {
            // 发起注册请求
            const { account, password } = this.ruleForm
            userReg({ account, password }).then((data) => {
              if (data.status != 0) return this.$message.error(data.message)
              return this.$message.success(data.message)
            })

            // 清空输入框
            this.$refs[formName].resetFields()
            this.ruleForm.checkPass = ''
          }
        }
      })
    },
    loginBox() {
      this.isShowR = false
      this.isShowL = true
    },
    registerBox() {
      this.isShowR = true
      this.isShowL = false
    },
  },
}
</script>

<style lang="less" scoped>
// @import '@/assets/styles/code.css';
.login-box {
  width: 100%;
  height: 100%;
  background-image: url('@/assets/image/bgi.jpeg');
  background-repeat: no-repeat;
  background-size: cover;
  box-sizing: border-box;
  padding-top: 200px;
  .loginForm {
    width: 400px;
    padding: 20px;
    border-radius: 20px;
    // background: #fff;
    background-color: rgba(255, 255, 255, 0.5);
    margin: 0 auto;
    h1 {
      text-align: center;
      margin: 20px 0;
      color: #606266;
    }
    .sub-btn {
      margin-left: 40px;
      width: 100px;
    }
  }
}
.code_box {
  display: flex;
}
#canvas {
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 5px;
  cursor: pointer;
  margin-right: 80px;
}
</style>
